package com.cccyy.encry;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;

public class SM4Example {
    private static final String ALGORITHM_NAME = "SM4";
    private static final String ALGORITHM_MODE = "SM4/ECB/PKCS5Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 生成 SM4 密钥
     *
     * @return 密钥的 Base64 编码字符串
     * @throws Exception 异常
     */
    public static String generateKey() throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, "BC");
        kg.init(128);
        SecretKey secretKey = kg.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * SM4 加密
     *
     * @param plainText 明文
     * @param key       密钥的 Base64 编码字符串
     * @return 密文的 Base64 编码字符串
     * @throws Exception 异常
     */
    public static String encrypt(String plainText, String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * SM4 解密
     *
     * @param cipherText 密文的 Base64 编码字符串
     * @param key        密钥的 Base64 编码字符串
     * @return 明文
     * @throws Exception 异常
     */
    public static String decrypt(String cipherText, String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE, "BC");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] cipherBytes = Base64.getDecoder().decode(cipherText);
        byte[] decryptedBytes = cipher.doFinal(cipherBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {

        // 生成随机16字节密钥
        SecureRandom random = new SecureRandom();
        KeyGenerator keyGen = KeyGenerator.getInstance("SM4");
        keyGen.init(128, random);
        SecretKey secretKey = keyGen.generateKey();
        byte[] keyBytes = secretKey.getEncoded();
        System.out.println("加密后密钥：" + Base64.getEncoder().encodeToString(keyBytes));

        try {
            // 生成密钥
            String key = generateKey();
            System.out.println("生成的密钥: " + key);

            // 明文
            String plainText = "Hello, SM4!";
            System.out.println("明文: " + plainText);

            // 加密
            String cipherText = encrypt(plainText, key);
            System.out.println("密文: " + cipherText);

            // 解密
            String decryptedText = decrypt(cipherText, key);
            System.out.println("解密后的明文: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//vN9IodKHSWm4736vPpBY8Q==
//1234567890123456